package com.imaker.frame

import android.app.Activity
import android.app.Application
import com.alibaba.android.arouter.launcher.ARouter
import com.imaker.frame.utils.ScreenUtils
import com.imaker.frame.utils.ToastUtil
import com.tencent.mmkv.MMKV
import com.tencent.smtt.export.external.TbsCoreSettings
import com.tencent.smtt.sdk.QbSdk
import me.jessyan.autosize.AutoSizeConfig
import me.jessyan.autosize.onAdaptListener
import java.security.SecureRandom
import java.security.cert.X509Certificate
import javax.net.ssl.HttpsURLConnection
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager
import kotlin.properties.Delegates

/**
 * @Description:
 * @author ziheng
 * @date 2023/5/17 10:22
 */
class MyApplication: Application(){
    companion object {
        private var instance: MyApplication by Delegates.notNull()
        fun instance() = instance
    }

    override fun onCreate() {
        super.onCreate()
        instance = this
        ToastUtil.init(instance)
        initAutoSize()
        initMMKV()
        initARouter()
        handleSSLHandshake()
        initX5Webview()
    }

    private fun initMMKV() {
        MMKV.initialize(this)
    }

    /**
     * 横竖版适配，横版根据设计图使用1920 竖版使用1080
     */
    private fun initAutoSize() {
        AutoSizeConfig.getInstance().onAdaptListener = object : onAdaptListener {
            override fun onAdaptBefore(target: Any, activity: Activity?) {
                if (ScreenUtils.isPortrait(activity!!)) {
                    AutoSizeConfig.getInstance().designWidthInDp = ScreenUtils.SCREEN_WITH
                } else {
                    AutoSizeConfig.getInstance().designWidthInDp =
                        ScreenUtils.SCREEN_WITH_HORIZONTAL
                }
            }

            override fun onAdaptAfter(target: Any?, activity: Activity?) {}
        }
    }
    private fun initARouter() {
        if (BuildConfig.DEBUG) {
            ARouter.openLog()
            ARouter.openDebug()
        }
        ARouter.init(this)
    }

    /**
     * 忽略https的证书校验
     */
    private fun handleSSLHandshake() {
        try {
            val trustAllCerts = arrayOf<TrustManager>(object : X509TrustManager {
                override fun getAcceptedIssuers(): Array<X509Certificate?> {
                    return arrayOfNulls<X509Certificate>(0)
                }

                override fun checkClientTrusted(
                    certs: Array<X509Certificate?>?,
                    authType: String?
                ) {
                }

                override fun checkServerTrusted(
                    certs: Array<X509Certificate?>?,
                    authType: String?
                ) {
                }
            })
            val sc = SSLContext.getInstance("TLS")
            // trustAllCerts信任所有的证书
            sc.init(null, trustAllCerts, SecureRandom())
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.socketFactory)
            HttpsURLConnection.setDefaultHostnameVerifier { hostname, session -> true }
        } catch (ignored: Exception) {
        }
    }

    private fun initX5Webview() {
        // 在调用TBS初始化、创建WebView之前进行如下配置
        val map = HashMap<String, Any>()
        map[TbsCoreSettings.TBS_SETTINGS_USE_SPEEDY_CLASSLOADER] = true
        map[TbsCoreSettings.TBS_SETTINGS_USE_DEXLOADER_SERVICE] = true
        QbSdk.initTbsSettings(map)
        QbSdk.initX5Environment(this, object : QbSdk.PreInitCallback {
            override fun onCoreInitFinished() {
                // 内核初始化完成
            }

            /**
             * 预初始化结束
             * 由于X5内核体积较大，需要依赖网络动态下发，所以当内核不存在的时候，默认会回调false，此时将会使用系统内核代替
             * @param isX5 是否使用X5内核
             */
            override fun onViewInitFinished(p0: Boolean) {
            }
        })
    }
}